<template>
  <div v-if="captchaOpen" >
    <CodeCaptcha ref="codeCaptcha" v-if="isCodeCaptcha" :username="username"/>
    <PictureCaptcha ref="pictureCaptcha" v-else @success="success"/>
  </div>
</template>

<script>
import {getCaptchaOpen} from '@/api/verify';
import CodeCaptcha from './CodeCaptcha'
import PictureCaptcha from './PictureCaptcha'

  export default {
    name: "captcha",
    components:{
      CodeCaptcha,
      PictureCaptcha
    },
    props:{
      username:{
        type: String,
      }
    },
    data() {
      return {
        captchaOpen: false,
        captchaCategory: '',
        captchaType: '',
      };
    },
    watch:{
    },
    created() {
    },
    mounted(){
      this.init()
    },
    computed:{
      isCodeCaptcha(){
        return this.captchaCategory == 'c';
      }
    },
    methods: {
      /** 获取验证码开关，并初始化 */
      init () {
        getCaptchaOpen().then(res => {
          this.captchaOpen = res.data.open
          this.captchaCategory = res.data.category
          this.captchaType = res.data.captchaType
          this.$nextTick(()=>{
            this.refreshCode()
          })
        }).catch(() => {})
      },
      refreshCode(){
        if(this.captchaOpen){
          this.getCaptchaInst().refreshCode(this.captchaType);
        }
      },
      success(params) {
        params.category = this.captchaCategory;
        this.$emit("success", params)
      },
      getCaptchaInst(){
        return this.isCodeCaptcha ? this.$refs.codeCaptcha : this.$refs.pictureCaptcha;
      },
      valid(){
        return this.captchaOpen?this.getCaptchaInst().valid(): '';
      },
      getCaptchaInfo(){
        if(this.captchaOpen){
          let data = this.getCaptchaInst().getCaptchaInfo();
          data.category = this.captchaCategory;
          return data;
        }
        return null;
      },
    }
  };
</script>
